package com.zh.chat.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.zh.chat.dao.UserDAO;
import com.zh.chat.entity.User;
import com.zh.chat.entity.UserStatus;
import com.zh.chat.convert.MD5Util;

public class UserDAOImpl implements UserDAO {
	private Logger log = Logger.getLogger(UserDAOImpl.class);
	private Configuration config = new Configuration().configure();
	private SessionFactory factory = config.buildSessionFactory();

	public UserDAOImpl() {
		log.info("UserServiceImpl初始化完成");
	}

	@Override
	public User register(User user) {
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		User newuser = null;
		String pStr = user.getUserPwd();
		String eStr = MD5Util.getMD5String(pStr);
		user.setUserPwd(eStr);
		user.setRegisterDate(new java.util.Date());
		user.setLastLoginDate(new java.util.Date());
		try {
			session.save(user);
			Long s = user.getSysId();
			if (s != null) {
				tx.commit();
				newuser = user;
			} else {
				throw new HibernateException("fail");
			}
		} catch (HibernateException e) {
			tx.rollback();
			log.error("添加用户失败" + e);
		} finally {
			session.close();
		}
		return newuser;
	}

	@Override
	public User login(Long id, String pwd) {
		Session session = factory.openSession();
		User user = null;
		session.beginTransaction();
		String hql = "from User where sysId=:sysId";
		Query query = session.createQuery(hql);
		query.setLong("sysId", id);
		user = (User) session.get(User.class, id);
		if (user != null) {
			session.close();
			boolean ok = MD5Util.checkPassword(pwd, user.getUserPwd());
			if (ok) {
				return user;
			}
		}
		return null;
	}

	@Override
	public User logout(Long id) {
		User user = findById(id);
		user.setStatus(UserStatus.OUTLINE);
		updateUser(user);//保存用户登出状态
		log.info("用户"+id+"登出");
		return null;
	}
	
	@Override
	public User updateUser(User user) {
		User newuser = null;
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		try {
			session.merge(user);
			tx.commit();
			newuser = user;
		} catch (HibernateException e) {
			tx.rollback();
			log.error("更新用户失败\n" + e);
			return null;
		} finally {
			session.close();
		}
		return newuser;
	}

	@Override
	public User deleteUser(User user) throws RuntimeException {
		Session session = factory.getCurrentSession();
		Transaction tx = session.beginTransaction();
		String err = null;
		User u = (User) session.get(User.class, user.getSysId());
		if (u != null) {
			try {
				session.delete(u);
				log.info("\n删除用户:\n" + u.toString() + "\n成功");
				tx.commit();
			} catch (Exception e) {
				tx.rollback();
				log.error("删除用户失败" + e);
				e.printStackTrace();
			} finally {
				session.close();
			}
		} else {
			throw new RuntimeException("删除的用户不存在");
		}
		return u;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll(String... condition) {
		List<User> list = null;
		Session session = factory.getCurrentSession();
		session.beginTransaction();
		String hql = "from User";
		Query query = session.createQuery(hql);
		list = query.list();
		session.close();
		return list;
	}

	@Override
	public User findById(Long id) {
		Session session = factory.openSession();
		session.beginTransaction();
		User user = (User) session.get(User.class, id);
		session.close();
		return user;
	}
}
